<?php
class Campaign extends Controller{
    public $data;
    function __construct(){
        parent::__construct();
        Session::init();
        $this->bar = new Bar();
        $this->model("model_website");
    }

    public function index(){
        //Set url begin login
        Session::set("url", "campaign");
        Session::commit();

        $data = $this->model_website->getCampaignInProgress();

        //Bar content
        $bar_content = $this->bar->getBarCampaign();
        $this->data['bar_content'] = $bar_content;

        //User
        if (Session::get("uid")){
            $user = $this->model_website->getUsersById(Session::get("uid"));
            $this->data['user'] = $user;
        }

        $this->data['view'] = "campaign";
        $this->data['category'] = "campaign";
        /*$this->data['type'] = "campaign";*/
        $this->data['title'] = "Chiến dịch";
        $this->data['data'] = $data;
        $this->view->render("layout/body", $this->data);
    }

    public function detail($cid, $url){
        //Set url begin login
        Session::set("url", "campaign/".$cid."-".$url);
        Session::commit();

        $data = $this->model_website->getCampaignByIdAndSlug($cid, $url);
        if($data){

            $images = $this->model_website->getImagesByCid($cid);
            $data[0]['images'] = $images;

            //Bar content
            $bar_content = $this->bar->getBarCampaignPage($data);
            $this->data['bar_content'] = $bar_content;

            //User
            if (Session::get("uid")){
                $user = $this->model_website->getUsersById(Session::get("uid"));
                $this->data['user'] = $user;
            }

            $this->data['cid'] = $cid;
            $this->data['view'] = "campaign_page";
            $this->data['category'] = "campaign";
        }else{
            $this->data['view'] = "error";
        }
        $this->data['title'] = "Chiến dịch";
        $this->data['data'] = "";
        $this->view->render("layout/body", $this->data);
    }

    public function getAnalytics(){
        $this->view->render("analytics/analytics", $this->data);

    }

    public function getComment(){

        $cid = 3;

        $uid = Session::get("uid");
        //Comment
        $comment = $this->model_website->getCommentByCid($cid);
        for($i = 0; $i < sizeof($comment); $i++){
            //Hiện thị thời gian của bình luận
            $today = new DateTime('now');
            $datetime = new DateTime($comment[$i]['comment_time']);
            $dateDiff   = $datetime->diff($today);
            $timeHour =  $dateDiff->format("%H");
            $timeMinutes = $dateDiff->format("%I");
            if($timeMinutes >= 60){
                if($timeHour > 24){
                    $interval = $datetime->diff($today);
                    $interval->format('%R%a');
                    if($interval > 2){
                        $comment[$i]['time'] = $datetime;
                    }else{
                        $comment[$i]['time'] = $interval." ngày trước";
                    }
                }else{
                    $comment[$i]['time'] = $timeHour." giờ trước";
                }
            }else{
                $comment[$i]['time'] = $timeMinutes." phút trước";
            }
            //Kiểm tra bình luận đã được like chưa
            $like = $this->model_website->getCommentLikeByCmidAndUid($comment[$i]['cmid'], $uid);
            if($like){
                $comment[$i]['like'] = "true";
            }else{
                $comment[$i]['like'] = "false";
            }

            $commentChild = $this->model_website->getCommentParent($comment[$i]['cmid']);
            if($commentChild){
                for($j = 0; $j < sizeof($commentChild); $j++){
                    //Hiện thị thời gian của các bình luận con
                    $today = new DateTime('now');
                    $date = new DateTime($commentChild[$j]['comment_time']);
                    $dteDiff   = $date->diff($today);
                    $hour =  intval($dteDiff->format("%H"));
                    $minutes = intval($dteDiff->format("%I"));
                    if($minutes >= 60){
                        if($hour > 24){
                            $interval = $date->diff($today);
                            $interval->format('%R%a');
                            if($interval > 2){
                                $commentChild[$j]['time'] = $date;
                            }else{
                                $commentChild[$j]['time'] = $interval." ngày trước";
                            }
                        }else{
                            $commentChild[$j]['time'] = $hour." giờ trước";
                        }
                    }else{
                        $commentChild[$j]['time'] = $minutes." phút trước";
                    }
                    //Kiểm tra bình luận đã được like chưa
                    $likeChild = $this->model_website->getCommentLikeByCmidAndUid($commentChild[$j]['cmid'], $uid);
                    if($likeChild){
                        $commentChild[$j]['like'] = "true";
                    }else{
                        $commentChild[$j]['like'] = "false";
                    }

                }
                $comment[$i]['children'] = $commentChild;
            }
        }
        $this->data['comment'] = $comment;

        $this->view->render("campaign/campaign_comment", $this->data);
    }

    public function addComment(){
        if(isset($_POST['text'])){
            $uid = Session::get("uid");
            if($uid){
                $cid = $_POST['cid'];
                $parent = $_POST['parent'];
                $comment_time = date("Y-m-d H:i:s");
                $text = $_POST['text'];
                $comment_media = "";
                $comment_like = 0;
                $comment = $this->model_website->addComment($cid, $parent, $uid, $text, $comment_time, $comment_media, $comment_like);
                if($comment){
                    echo json_encode(array("status"=>"ok", 'comment'=>$comment));
                }
            }else{
                echo json_encode(array("status"=>"signIn"));
            }
        }else{
            echo json_encode(array("status"=>"error"));
        }
    }

    public function addChildComment(){
        if(isset($_POST['id'])){
            $uid = Session::get("uid");
            if($uid){
                $cid = 0;
                $id = $_POST['id'];
                $content = $_POST['content'];
                $comment_time = date("Y-m-d H:i:s");
                $comment_media = "";
                $comment_like = 0;
                $comment = $this->model_website->addComment($cid, $id, $uid, $content, $comment_time, $comment_media, $comment_like);
                if($comment){
                    echo json_encode(array("status"=>"ok", 'comment'=>$comment));
                }
            }else{
                echo json_encode(array("status"=>"signIn"));
            }
        }else{
            echo json_encode(array("status"=>"error"));
        }
    }

    public function likeComment(){
        if(isset($_POST['id'])){
            $id = $_POST['id'];
            $uid = Session::get("uid");
            if($uid){
                $like = $this->model_website->getCommentLikeByCmidAndUid($id, $uid);
                if(!$like){
                    $time = date("Y-m-d H:i:s");
                    $this->model_website->addCommentLike($id, $uid, $time);
                    $this->model_website->updateLike($id);
                    $number = $this->model_website->getCommentById($id);
                    $num = 0;
                    if($number){
                        $num = $number[0]['comment_like'];
                    }
                    echo json_encode(array("status"=>"like", "number"=>$num));
                }else{
                    //Remove like
                    $this->model_website->removeCommentLike($id, $uid);
                    $this->model_website->updateUnlike($id);
                    $number = $this->model_website->getCommentById($id);
                    $num = 0;
                    if($number){
                        $num = $number[0]['comment_like'];
                    }
                    echo json_encode(array("status"=>"unlike", "number"=>$num));
                }
            }else{
                echo json_encode(array("status"=>"error"));
            }
        }else{
            echo json_encode(array("status"=>"error"));
        }
    }

    public function unlikeComment(){
        if(isset($_POST['id'])){
            $id = $_POST['id'];
            $uid = Session::get("uid");
            if($uid){
                $like = $this->model_website->getCommentLikeByCmidAndUid($id, $uid);
                if(!$like){
                    $this->model_website->removeCommentLike($id, $uid);
                    $this->model_website->updateUnlike($id);
                    echo json_encode(array("status"=>"ok"));
                }else{
                    echo json_encode(array("status"=>"error"));
                }
            }else{
                echo json_encode(array("status"=>"error"));
            }
        }else{
            echo json_encode(array("status"=>"error"));
        }
    }

    /*public function create(){

        //Chuyen chuoi co dau thanh link seo
        $url = mb_strtolower($this->url_title($this->removeSign("chuoi trong nay")));

        if(!empty($_POST)){
            $title = $_POST['title'];
            $description = $_POST['description'];
            $beginDate = $_POST['begin'];
            $endDate = $_POST['end'];
            $image = $_POST['image[]'];

        }

        $this->data['view'] = "campaign_create";
        $this->data['category'] = "campaign";
        $this->data['type'] = "campaign";
        $this->data['title'] = "TẠO CHIẾN DỊCH";
        $this->data['data'] = "";
        $this->view->render("layout/body", $this->data);
    }*/

    /*public function edit($str = ""){

        if($str){


            $this->data['view'] = "campaign_edit";
            $this->data['category'] = "campaign";
            $this->data['type'] = "campaign";
        }else{
            $this->data['view'] = "error";
        }

        $this->data['title'] = "CHỈNH SỬA CHIẾN DỊCH";
        $this->data['data'] = "";
        $this->view->render("layout/body", $this->data);
    }*/

    public function extract(){
        if(isset($_POST["url"]))
        {
            $get_url = $_POST["url"];

            //Include PHP HTML DOM parser (requires PHP 5 +)
            include_once("extract_dom.inc.php");

            //get URL content
            $get_content = file_get_html($get_url);

            //Get Page Title
            foreach($get_content->find('title') as $element)
            {
                $page_title = $element->plaintext;
            }

            //Get Body Text
            foreach($get_content->find('body') as $element)
            {
                $page_body = trim($element->plaintext);
                $pos=strpos($page_body, ' ', 200); //Find the numeric position to substract
                $page_body = substr($page_body,0,$pos ); //shorten text to 200 chars
            }

            $image_urls = array();

            //get all images URLs in the content
            foreach($get_content->find('img') as $element)
            {
                /* check image URL is valid and name isn't blank.gif/blank.png etc..
                you can also use other methods to check if image really exist */
                if(!preg_match('/blank.(.*)/i', $element->src) && filter_var($element->src, FILTER_VALIDATE_URL))
                {
                    $image_urls[] =  $element->src;
                }
            }

            //prepare for JSON
            $output = array('title'=>$page_title, 'images'=>$image_urls, 'content'=> $page_body);
            echo json_encode($output); //output JSON data
        }else{

        }
    }

    function removeSign($str)
    {
        $have=array("à","á","ạ","ả","ã","â","ầ","ấ","ậ","ẩ","ẫ","ă","ằ","ắ"
        ,"ặ","ẳ","ẵ","è","é","ẹ","ẻ","ẽ","ê","ề","ế","ệ","ể","ễ","ì","í","ị","ỉ","ĩ",
            "ò","ó","ọ","ỏ","õ","ô","ồ","ố","ộ","ổ","ỗ","ơ"
        ,"ờ","ớ","ợ","ở","ỡ",
            "ù","ú","ụ","ủ","ũ","ư","ừ","ứ","ự","ử","ữ",
            "ỳ","ý","ỵ","ỷ","ỹ",
            "đ",
            "À","Á","Ạ","Ả","Ã","Â","Ầ","Ấ","Ậ","Ẩ","Ẫ","Ă"
        ,"Ằ","Ắ","Ặ","Ẳ","Ẵ",
            "È","É","Ẹ","Ẻ","Ẽ","Ê","Ề","Ế","Ệ","Ể","Ễ",
            "Ì","Í","Ị","Ỉ","Ĩ",
            "Ò","Ó","Ọ","Ỏ","Õ","Ô","Ồ","Ố","Ộ","Ổ","Ỗ","Ơ"
        ,"Ờ","Ớ","Ợ","Ở","Ỡ",
            "Ù","Ú","Ụ","Ủ","Ũ","Ư","Ừ","Ứ","Ự","Ử","Ữ",
            "Ỳ","Ý","Ỵ","Ỷ","Ỹ",
            "Đ","ê","ù","à");
        $none=array("a","a","a","a","a","a","a","a","a","a","a"
        ,"a","a","a","a","a","a",
            "e","e","e","e","e","e","e","e","e","e","e",
            "i","i","i","i","i",
            "o","o","o","o","o","o","o","o","o","o","o","o"
        ,"o","o","o","o","o",
            "u","u","u","u","u","u","u","u","u","u","u",
            "y","y","y","y","y",
            "d",
            "A","A","A","A","A","A","A","A","A","A","A","A"
        ,"A","A","A","A","A",
            "E","E","E","E","E","E","E","E","E","E","E",
            "I","I","I","I","I",
            "O","O","O","O","O","O","O","O","O","O","O","O"
        ,"O","O","O","O","O",
            "U","U","U","U","U","U","U","U","U","U","U",
            "Y","Y","Y","Y","Y",
            "D","e","u","a");
        return str_replace($have,$none,$str);
    }

    function url_title($str, $separator = '-', $lowercase = FALSE)
    {
        if ($separator == 'dash')
        {
            $separator = '-';
        }
        else if ($separator == 'underscore')
        {
            $separator = '_';
        }

        $q_separator = preg_quote($separator);

        $trans = array(
            '&.+?;'                 => '',
            '[^a-z0-9 _-]'          => '',
            '\s+'                   => $separator,
            '('.$q_separator.')+'   => $separator
        );

        $str = strip_tags($str);

        foreach ($trans as $key => $val)
        {
            $str = preg_replace("#".$key."#i", $val, $str);
        }

        if ($lowercase === TRUE)
        {
            $str = strtolower($str);
        }

        return trim($str, $separator);
    }
}
?>